package com.bw.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.GiteeUtils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class GiteeBindController {

    @Autowired
    UserMapper userMapper;

    @RequestMapping("/callbackCode.do")
    public String callbackCode(String code, HttpServletRequest request, HttpServletResponse response){

        System.out.println("接收到的临时授权码：" + code);

        // 根据临时授权码获取token
        String tokenByCode = GiteeUtils.getAccessTokenByCode(code);
        System.out.println("获取到的token " + tokenByCode);
        // 根据token获取用户信息
        JSONObject userInfoByToken = GiteeUtils.getGiteeUserInfoByToken(tokenByCode);
        System.out.println("获取到的用户信息" + JSON.toJSONString(userInfoByToken));

        // 解析所需的字段  昵称 头像  id

        String avatarUrl = userInfoByToken.getString("avatar_url");
        String nickName = userInfoByToken.getString("name");
        Integer giteeId = userInfoByToken.getInteger("id");
        // 修改当前登录用户
        User userFromRequest = TokenUtils.getLoginUserFromRequest(request, User.class);
        userFromRequest.setGiteeId(giteeId);
        userFromRequest.setAvatarUrl(avatarUrl);
        userFromRequest.setNickName(nickName);

        userMapper.updateById(userFromRequest);

        // 重新制作令牌
        TokenUtils.responseTokenByCookie(userFromRequest,response);

        return "redirect:list.do";
    }
}
